package com.buyouchina.utils;

import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JSONString;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsDateJsonValueProcessor;
import net.sf.json.util.CycleDetectionStrategy;

public class ToJson {
	public static void OutJSONArray(HttpServletResponse response,
			List<?> areaList) {
		JSONArray json = (JSONArray) JSONSerializer.toJSON(areaList);
		outPut(response, json);
	}

	public static void OutJSONArray1(HttpServletResponse response,
			List<?> areaList, JsonConfig config) {
		JSONArray json = (JSONArray) JSONSerializer.toJSON(areaList, config);
		outPut(response, json);
	}

	public static void OutJSONString(HttpServletResponse response, String[] str) {
		JSONArray json = (JSONArray) JSONSerializer.toJSON(str);
		outPut(response, json);
	}

	public static void OutJSONObject(HttpServletResponse response, Object obj) {
		JSONObject json = (JSONObject) JSONSerializer.toJSON(obj, config());
		outPut(response, json);
	}

	public static void OutJSONObject1(HttpServletResponse response, Object obj,
			JsonConfig config) {
		JSONObject json = (JSONObject) JSONSerializer.toJSON(obj, config);
		outPut(response, json);
	}

	public void OutJSONString(HttpServletResponse response, String obj) {
		JSONString json = (JSONString) JSONSerializer.toJSON(obj);
		outPut(response, json);
	}

	public static void outPut(HttpServletResponse response, Object json) {
		try {
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			out.print(json);
			System.out.print(json);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static JsonConfig config() {
		JsonConfig config = new JsonConfig(); // jsonConfig 解析级联json错误
		config.setIgnoreDefaultExcludes(false);
		config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
		config.registerJsonValueProcessor(Date.class,
				new JsDateJsonValueProcessor());
		config.setExcludes(new String[] {// 只要设置这个数组，指定过滤哪些字段。
				"products", "category", "outlets" });
		return config;
	}
}
